<?php

namespace common\models;

use Yii;
use yii\db\Exception;
use yii\db\Query;

/**
 * This is the model class for table "package_application".
 *
 * @property string $id
 * @property string $package_id
 * @property integer $type
 * @property integer $proposer
 * @property string $applied_at
 * @property string $reason
 * @property integer $workflow_status
 * @property integer $is_package
 */
class PackageApplication extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'package_application';
    }

    /*关联表 审核结果application_result*/
    public function getResult()
    {
        return $this->hasOne(ApplicationResult::className(), ['application_id' => 'id']);
    }

    /*关联表 资产包 package*/
    public function getPackage()
    {
        return $this->hasOne(Package::className(), ['id' => 'package_id']);
    }

    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'proposer']);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_id', 'type', 'proposer'], 'required'],
            [['package_id', 'type', 'proposer', 'workflow_status', 'is_package'], 'integer'],
            [['applied_at'], 'safe'],
            [['reason'], 'string'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'package_id' => '资产包Id',
            'type' => '审批名称',
            'proposer' => '申请人',
            'applied_at' => '申请时间',
            'reason' => '申请理由',
            'workflow_status' => '审批进程',
            'is_package' => '中否资产包',
        ];
    }

    /**
     * 获取数量
     * @param $where
     * @return int
     */
    public function getCounts($where = '')
    {
        $sql = 'SELECT count(application.id) FROM
                    (SELECT pa.*,ar.id AS result_id,ar.result,u.realname,ar.user_id AS user,p.title AS application_tilte FROM package_application pa 
                    LEFT JOIN application_result ar ON pa.id=ar.application_id
                    LEFT JOIN user AS u ON pa.proposer=u.id
                    LEFT JOIN package p ON pa.package_id=p.id
                    WHERE pa.is_package=1
                    UNION
                    SELECT pa.*,ar.id AS result_id,ar.result,u.realname,ar.user_id AS user,p.title AS application_tilte FROM package_application pa 
                    LEFT JOIN application_result ar ON pa.id=ar.application_id
                    LEFT JOIN user AS u ON pa.proposer=u.id
                    LEFT JOIN project p ON pa.package_id=p.id
                    WHERE pa.is_package=2) AS application';

        if ($where != '') {
            $sql .= $where;
        }

        return Yii::$app->db->createCommand($sql)->queryColumn();
    }

    /**
     * 获取列表
     * @param string $where
     * @param string $group
     * @param string $order
     * @param int $limit
     * @return array
     */
    public function getList($where = '', $group = '', $order = 'ORDER BY  application.id DESC', $limit = 10)
    {
        $sql = 'SELECT application.* FROM
                    (SELECT pa.*,ar.id AS result_id,ar.result,ar.note,u.realname,ar.user_id AS user,p.title AS application_tilte FROM package_application pa 
                    LEFT JOIN application_result ar ON pa.id=ar.application_id
                    LEFT JOIN user AS u ON pa.proposer=u.id
                    LEFT JOIN package p ON pa.package_id=p.id
                    WHERE pa.is_package=1
                    UNION
                    SELECT pa.*,ar.id AS result_id,ar.result,ar.note,u.realname,ar.user_id AS user,p.title AS application_tilte FROM package_application pa 
                    LEFT JOIN application_result ar ON pa.id=ar.application_id
                    LEFT JOIN user AS u ON pa.proposer=u.id
                    LEFT JOIN project p ON pa.package_id=p.id
                    WHERE pa.is_package=2) AS application';

        if ($where != '') {
            $sql .= $where;
        }

        if ($group != '') {
            $sql .= $group;
        }

        if ($order != '') {
            $sql .= $order;
        }

        if ($limit != '') {
            $sql .= $limit;
        }

        $list = Yii::$app->db->createCommand($sql)->queryAll();

        if (!empty($list) && is_array($list)) {
            $auditType = Yii::$app->params['auditType'];
            $audit_result = Yii::$app->params['audit_result'];
            $userModel = new UserModel();
            $userList = $userModel->getDepartmentUsersList();

            foreach ($list as $key => $value) {
                $list[$key]['type'] = $auditType[$value['type']];
                if ($value['result'] > 0) {
                    $list[$key]['result'] = $audit_result[(string)$value['result']];
                }

                $list[$key]['applied_at'] = date('Y/m/d H:i', strtotime($value['applied_at']));

                switch ($value['type']) {
                    case 1:
                        if ($value['user'] > 0) {
                            $list[$key]['user'] = $userList[$value['user']]['description'] . '-' . $userList[$value['user']]['realname'];
                        } else {
                            $spzy = '';
                            $roleModel = (new \yii\db\Query())->from('auth_assignment as aa')->leftJoin('user as u','aa.user_id = u.id')->where(['in','item_name','Projectapprovalspecialist'])->all();
                            if (!empty($roleModel)) {
                                foreach ($roleModel as $k => $v) {
                                    $spzy .= $v['realname'].' ';
                                }
                            }

                            $list[$key]['user'] = $spzy;
                        }
                        break;
                    case 5:
                        if ($value['user'] > 0) {
                            $list[$key]['user'] = $userList[$value['user']]['description'] . '-' . $userList[$value['user']]['realname'];
                        } else {
                            $user_id = 0;
                            switch ($value['is_package']) {
                                //资产包
                                case 1:
                                    $package_initiation = PackageInitiation::find()->where(['package_id'=>(int)$value['package_id']])->one();
                                    if ($package_initiation->leader >0 ) {
                                        $user_id = $package_initiation->leader;
                                    } else {
                                        $package = Package::findOne((int)$value['package_id']);
                                        $user_id = $package->owner;
                                    }
                                    break;
                                //单项目
                                case 2:
                                    $project_team = ProjectTeam::find()->where(['project_id'=>(int)$value['package_id']])->one();
                                    if ($project_team !== null && $project_team->owner > 0 ) {
                                        $user_id = $project_team->owner;
                                    } else {
                                        $project = Project::findOne((int)$value['package_id']);
                                        if ($project !== null) {
                                            $package_initiation = PackageInitiation::find()->where(['package_id'=>$project->package_id])->one();
                                            if ($package_initiation !== null && $package_initiation->leader >0 ) {
                                                $user_id = $package_initiation->leader;
                                            } else {
                                                $package = Package::findOne((int)$value['package_id']);
                                                if ($package !== null && $package->owner > 0) {
                                                    $user_id = $package->owner;
                                                }
                                            }
                                        }
                                    }
                                    break;
                                default:
                            }
                            if ($user_id > 0) {
                                $list[$key]['user'] = $userList[(int)$user_id]['description'] . '-' . $userList[(int)$user_id]['realname'];
                            } else {
                                $list[$key]['user']  = '';
                            }
                        }
                        break;
                    default:
                        $list[$key]['user'] = '';
                }
            }
        }
        return $list;
    }

    /**
     * @param $id ID
     * @param $package_id 资产包ID
     * @param $userId 用户ID
     * @param $type 申请类型
     * @return array 返回结果
     */
    public function addPackageLog($id, $package_id, $userId, $type)
    {
        try {
            $user = '';
            $auditType = Yii::$app->params['auditType'];
            $list = (new UserModel())->getDepartmentUsersList(['user.id' => $userId]);
            if (!empty($list) && is_array($list)) {
                $user = $list[$userId]['description'] . '-' . $list[$userId]['realname'];
            }

            if ($type != 5) {
                $log = "{$user} 申请{$auditType[(int)$type]}";
            } else {
                $log = "{$user} 申请访问";
            }

            $packageLog = new PackageLog();
            $packageLog->package_id = $package_id;
            $packageLog->created_at = date('Y-m-d H:i:s', time());
            $packageLog->user_id = $userId;
            $packageLog->log = $log;
            if (!$packageLog->save()) {
                $error = $packageLog->getFirstErrors();
                $message = '';
                if (!empty($error)) {
                    foreach ($error as $value) {
                        $message .= $value;
                    }
                    $tmpStr = strip_tags($message);
                    $tmpLen = mb_strlen($tmpStr);
                    $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                }
                throw new \Exception($message);
            }
            return array('state' => true, 'msg' => '添加日志成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }

}
